﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Runda.CMS.Common.Entity;
using System.Collections.Generic;
using Runda.CMS.Bll;
using Telerik.WebControls;
using Runda.CMS.Common.Utility;


namespace Runda.CMS.Portal.ContractManage
{
    public partial class ContractItemListSaleView : BasePage
    {
        public Guid ContractID
        {
            get
            {
                if (Request.QueryString["ContractID"] != null)
                {
                    return new Guid(Request.QueryString["ContractID"]);
                }
                return Guid.Empty;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["ContractID"] != null)
                {
                    ddlPaymentType.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.ContractPaymentType)));
                    txtContractID.Value = Request.QueryString["ContractID"];

                    InitContractInfo();

                    BindContractItem(string.Empty);

                    BindContractGift();
                }
            }
        }

        private void BindContractItem(string OrderBy)
        {
            ContractBll bll = new ContractBll();
            DataTable dt = bll.GetContractItemTable(" and ContractID = '" + Request.QueryString["ContractID"] + "'", OrderBy);

            gridContractItems.DataSource = dt;
            gridContractItems.DataBind();
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            BindContractItem(string.Empty);
        }

        protected void gridContractItems_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            {
                TextBox txtCount = e.Item.FindControl("txtCount") as TextBox;
                DataRowView dv = e.Item.DataItem as DataRowView;

                if (dv["Type"] != DBNull.Value && dv["Type"] != null && Convert.ToInt32(dv["Type"].ToString()) == 2)
                {
                    txtCount.Enabled = false;
                }

            }
        }

        protected void gridContractItems_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.Item.ItemIndex < 0) return;
            if (e.CommandName == "save")
            {
                Guid ItemID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ItemID"].ToString());
                TextBox txtGuaranteeYear = e.Item.FindControl("txtGuaranteeYear") as TextBox;
                TextBox txtCount = e.Item.FindControl("txtCount") as TextBox;
                TextBox txtPrice = e.Item.FindControl("txtPrice") as TextBox;
                if (txtGuaranteeYear == null) return;
                if (txtCount == null) return;
                if (txtPrice == null) return;

                int GuaranteeYear = 0;
                if (txtGuaranteeYear.Text.Trim() != string.Empty)
                {
                    if (int.TryParse(txtGuaranteeYear.Text.Trim(), out GuaranteeYear))
                    {
                        GuaranteeYear = Convert.ToInt32(txtGuaranteeYear.Text.Trim());
                    }
                }

                decimal Count = 0;
                if (txtCount.Text.Trim() != string.Empty)
                {
                    if (decimal.TryParse(txtCount.Text.Trim(), out Count))
                    {
                        Count = Convert.ToDecimal(txtCount.Text.Trim());
                    }
                }

                decimal Price = 0;
                if (txtPrice.Text.Trim() != string.Empty)
                {
                    if (decimal.TryParse(txtPrice.Text.Trim(), out Price))
                    {
                        Price = Convert.ToDecimal(txtPrice.Text.Trim());
                    }
                }
                CtrtContractItemBll bll = new CtrtContractItemBll();
                CtrtContractItemEntity entity = bll.Get<CtrtContractItemEntity>(ItemID);
                entity.GuaranteeYear = GuaranteeYear;
                entity.Count = Count;
                entity.Price = Price;
                entity.TotalPrice = Count * Price;
                bll.Update(entity);
                BindContractItem(string.Empty);
            }
            if (e.CommandName == "delete")
            {
                Guid ItemID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ItemID"].ToString());
                ContractBll bll = new ContractBll();
                bll.DeleteContractItem(ItemID);
                BindContractItem(string.Empty);
                BindGuaranty();
            }
        }

        protected void gridContractItems_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = " Order by " + e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            BindContractItem(OrderBy);
        }

        private void BindGuaranty()
        {
            if (txtItemID.Value != string.Empty)
            {
                //gridGuaranty.DataSource = new CtrtItemGuarantyBll().GetAll<CtrtItemGuarantyEntity>(" and ItemID ='" + txtItemID.Value + "'");
                //gridGuaranty.DataBind();
            }
        }

        protected void gridGuaranty_DeleteCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            Guid GuarantyID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["GuarantyID"].ToString());

            CtrtItemGuarantyBll bll = new CtrtItemGuarantyBll();
            bll.Delete(new CtrtItemGuarantyEntity(GuarantyID));
            BindGuaranty();

        }

        protected void btnSavePayment_Click(object sender, EventArgs e)
        {
            List<CtrtContractPaymentEntity> ContractPayList = new List<CtrtContractPaymentEntity>();
            foreach (GridItem item in gridPayment.Items)
            {
                if (item.ItemType == GridItemType.Item || item.ItemType == GridItemType.AlternatingItem)
                {
                    Guid PaymentID = new Guid(item.OwnerTableView.DataKeyValues[item.ItemIndex]["PaymentID"].ToString());
                    RadDatePicker txtPayDate = item.FindControl("txtPayDate") as RadDatePicker;
                    RadNumericTextBox txtPayAmount = item.FindControl("txtPayAmount") as RadNumericTextBox;

                    CtrtContractPaymentEntity PayEntity = new CtrtContractPaymentEntity();
                    PayEntity.PaymentID = PaymentID;
                    PayEntity.ContractID = new Guid(txtContractID.Value);
                    if (txtPayDate.SelectedDate.HasValue)
                        PayEntity.PayDate = txtPayDate.SelectedDate.Value;

                    if (txtPayAmount.Value.HasValue)
                        PayEntity.PayAmount = Convert.ToDecimal(txtPayAmount.Value.Value);

                    PayEntity.CreatedAt = DateTime.Now;
                    PayEntity.CreatedBy = base.CurrentUserID;
                    ContractPayList.Add(PayEntity);
                }
            }

            if (ContractPayList.Count == 0)
            {
                //RadAjaxManager1.Alert("");
                //return;
            }

            ContractBll bll = new ContractBll();
            CtrtContractEntity entity = bll.Get<CtrtContractEntity>(new Guid(txtContractID.Value));
            entity.PaymentType = Convert.ToByte(ddlPaymentType.SelectedValue);
            entity.PaymentPeriod = Convert.ToInt32(ddlPaymentPeroid.SelectedValue);

            bll.SaveContractPayment(entity, ContractPayList);

            RadAjaxManager1.Alert("合同付款信息保存成功!");
        }

        protected void ddlPaymentType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Convert.ToInt32(ddlPaymentType.SelectedValue) == (int)Enumerator.ContractPaymentType.Disposable)
            {
                ddlPaymentPeroid.SelectedValue = "1";
                ddlPaymentPeroid.Enabled = false;
            }
            else
            {
                ddlPaymentPeroid.Enabled = true;
            }
        }

        protected void ddlPaymentPeroid_SelectedIndexChanged(object sender, EventArgs e)
        {
            ContractBll bll = new ContractBll();
            if (bll.BuildContractPayment(new Guid(txtContractID.Value), Convert.ToInt32(ddlPaymentPeroid.SelectedValue)))
            {
                BindPaymentGrid();
            }
        }

        protected void gridPayment_DeleteCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                Guid PaymentID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["PaymentID"].ToString());

                CtrtContractPaymentBll bll = new CtrtContractPaymentBll();
                bll.Delete<CtrtContractPaymentEntity>(" and PaymentID = '" + PaymentID + "'");
                BindPaymentGrid();
            }
        }

        private void BindPaymentGrid()
        {
            if (txtContractID.Value == "") return;

            CtrtContractPaymentBll bll = new CtrtContractPaymentBll();
            gridPayment.DataSource = bll.GetAll<CtrtContractPaymentEntity>(" and ContractID = '" + txtContractID.Value + "'");
            gridPayment.DataBind();
        }

        private void InitContractInfo()
        {
            if (txtContractID.Value == "") return;

            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractEntity entity = bll.Get<CtrtContractEntity>(new Guid(txtContractID.Value));
            if (entity != null)
            {
                ddlPaymentType.SelectedValue = entity.PaymentType.ToString();
                ddlPaymentPeroid.SelectedValue = entity.PaymentPeriod.ToString();
            }
            ddlPaymentType_SelectedIndexChanged(null, null);
            ddlPaymentPeroid_SelectedIndexChanged(null, null);
            BindPaymentGrid();
        }

        protected void gridPayment_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                Guid PaymentID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["PaymentID"].ToString());
                RadDatePicker txtPayDate = e.Item.FindControl("txtPayDate") as RadDatePicker;
                RadNumericTextBox txtPayAmount = e.Item.FindControl("txtPayAmount") as RadNumericTextBox;

                CtrtContractPaymentEntity entity = e.Item.DataItem as CtrtContractPaymentEntity;
                if (entity != null)
                {
                    if (entity.PayDate != DateTime.MinValue)
                        txtPayDate.SelectedDate = entity.PayDate;

                    if (entity.PayAmount != decimal.MinValue)
                        txtPayAmount.Value = (double)entity.PayAmount;
                }
            }
        }

        protected void btnRefreshContractGift_Click(object sender, EventArgs e)
        {
            BindContractGift();
        }

        private void BindContractGift()
        {
            ContractBll bll = new ContractBll();
            gridContractGift.DataSource = bll.LoadContractGift(ContractID);
            gridContractGift.DataBind();
        }

        protected void gridContractGift_DeleteCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                Guid GiftID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["GiftID"].ToString());
                ContractBll bll = new ContractBll();
                bll.Delete(new CtrtContractGiftEntity(GiftID));

                BindContractGift();
            }
        }

        protected void gridContractItemPart_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.Item.ItemIndex < 0) return;
            if (e.CommandName == "save")
            {
                Guid PartID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["PartID"].ToString());
                RadNumericTextBox txtCount = e.Item.FindControl("txtCount") as RadNumericTextBox;

                ContractBll bll = new ContractBll();
                CtrtContractItemPartEntity entity = bll.Get<CtrtContractItemPartEntity>(PartID);
                entity.Count = txtCount.Value.HasValue ? (int)txtCount.Value.Value : 0;
                bll.Update(entity);
                //btnResreshItemPart_Click(null, null);
            }
        }

        protected void gridContractItemPart_DeleteCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                Guid PartID = new Guid(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["PartID"].ToString());
                ContractBll bll = new ContractBll();
                bll.Delete(new CtrtContractItemPartEntity(PartID));

                //btnResreshItemPart_Click(null, null);
            }
        }

        protected void gridContractItemPart_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                DataRowView dv = e.Item.DataItem as DataRowView;
                if (dv != null)
                {
                    RadNumericTextBox txtCount = e.Item.FindControl("txtCount") as RadNumericTextBox;
                    txtCount.Value = Convert.ToDouble(dv["count"].ToString());
                }
            }
        }

        protected void btnResreshItemPart_Click(object sender, EventArgs e)
        {
            if (txtItemID.Value == "") return;
            ContractBll bll = new ContractBll();
            DataTable dt = bll.GetContractItemPart(new Guid(txtItemID.Value));

            //gridContractItemPart.DataSource = dt;
            //gridContractItemPart.DataBind();
        }
    }
}
